<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserApi } from '@/api/user/index'
import { useRoleApi } from '@/api/role/index'

const userApi = useUserApi()
const roleApi = useRoleApi()

// 状态管理
const userFormRef = ref()
const roleTableRef = ref()
const state = reactive({
  loading: false,
  pageIndex: 1,
  pageSize: 6,
  page: {
    records: [],
    total: 0
  },
  searchParams: {
    username: '',
    gender: undefined,
    status: undefined,
    mobile: '',
    email: ''
  },
  selectionIds: [],

  showEdit: false,
  dialogTitle: '',
  userForm: {
    id: undefined,
    username: '',
    password: '',
    realName: '',
    gender: 0,
    mobile: '',
    email: '',
    status: 0,
    remark: ''
  },
  userRules: {
    username: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
    password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    mobile: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: '手机号码格式错误',
        trigger: ['blur', 'change']
      }
    ],
    email: [{ type: 'email', message: '邮箱格式错误', trigger: 'blur' }]
  },

  assignTitle: '',
  assignVisible: false,
  roleData: [],
  assignUserId: undefined,
  roleSelectionIds: []
})

// 获取表格数据
const getTableData = async (current = 1) => {
  try {
    state.loading = true
    state.pageIndex = current
    const params = { pageIndex: state.pageIndex, pageSize: state.pageSize }
    state.page = await userApi.getPage(params, state.searchParams)
  } finally {
    state.loading = false
  }
}

// 重置查询
const resetSearch = () => {
  state.searchParams = {
    username: '',
    gender: undefined,
    status: undefined,
    mobile: '',
    email: ''
  }
  getTableData()
}

// 处理分页大小改变
const handleSizeChange = async (val) => {
  state.pageSize = val
  await getTableData()
}

// 处理复选框选中
const handleSelectionChange = (rows) => {
  state.selectionIds = rows.map((v) => v.id)
}

// 打开编辑弹窗
const openEdit = (row) => {
  state.showEdit = true
  state.dialogTitle = '添加用户'
  if (row) {
    state.dialogTitle = '修改用户'
    state.userForm = { ...row }
  }
}

// 处理弹窗关闭
const handleClose = () => {
  userFormRef.value.resetFields()
}

// 处理提交
const handleSubmit = async () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      if (state.userForm.id) {
        await userApi.update(state.userForm)
      } else {
        await userApi.save(state.userForm)
      }
      state.showEdit = false
      ElMessage.success('操作成功')
      await getTableData()
    }
  })
}

// 处理删除
const handleRemove = (ids) => {
  ElMessageBox.confirm('确认要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await userApi.remove(ids)
    ElMessage.success('删除成功')
    await getTableData()
  })
}

// 打开分配角色弹窗
const openAssign = async (row) => {
  state.assignVisible = true
  state.assignTitle = `${row.realName} 分配角色`
  state.assignUserId = row.id

  state.roleData = await roleApi.getList()

  nextTick(async () => {
    const res = await userApi.getById(row.id)
    state.selectionIds = res.roles.map((v) => v.id)
    state.roleData.forEach((role) => {
      if (state.selectionIds.indexOf(role.id) != -1) {
        roleTableRef.value?.toggleRowSelection(role, true)
      }
    })
  })
}

// 处理角色选择
const handleRoleCheck = (rows) => {
  state.roleSelectionIds = rows.map((v) => v.id)
}

// 分配角色
const assignRole = async () => {
  if (state.roleSelectionIds.length === 0) {
    ElMessage.warning('请选择角色')
  } else {
    await userApi.assignRole({
      userId: state.assignUserId,
      roleIds: state.roleSelectionIds
    })
    ElMessage.success('分配成功')
    state.assignVisible = false
  }
}

// 初始化加载用户
onMounted(() => {
  getTableData()
})
</script>

<template>
  <el-card shadow="never">
    <el-row>
      <el-form :model="state.searchParams" :inline="true">
        <el-row>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="用户名称" prop="username">
              <el-input v-model="state.searchParams.username" placeholder="请输入用户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="state.searchParams.phone" placeholder="请输入手机号码" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="state.searchParams.email" placeholder="请输入电子邮箱" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="用户性别" prop="gender">
              <el-select
                style="width: 190px"
                v-model="state.searchParams.gender"
                placeholder="请选择用户性别"
                clearable
              >
                <el-option :value="0" label="保密" />
                <el-option :value="1" label="男" />
                <el-option :value="2" label="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="用户状态" prop="status">
              <el-select
                style="width: 190px"
                v-model="state.searchParams.status"
                placeholder="请选择用户状态"
                clearable
              >
                <el-option :value="0" label="启用" />
                <el-option :value="1" label="禁用" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item>
              <el-button type="primary" @click="getTableData()">
                <el-icon><Search /></el-icon> 搜索
              </el-button>
              <el-button @click="resetSearch">
                <el-icon><Refresh /></el-icon> 清空
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>

    <el-row>
      <el-button v-auth="'user:save'" type="primary" icon="plus" @click="openEdit(null)"> 添加用户 </el-button>
      <el-button v-auth="'user:delete'" type="danger" icon="delete" @click="handleRemove(state.selectionIds)">
        批量删除
      </el-button>
    </el-row>

    <el-table
      class="mt10"
      :loading="state.loading"
      element-loading-text="正在努力加载数据中..."
      :data="state.page.records"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />

      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="username" label="用户名称" min-width="120" />
      <el-table-column prop="realName" label="真实姓名" min-width="120" />
      <el-table-column props="avatar" label="头像">
        <template #default="{ row }">
          <el-image
            style="width: 40px; height: 40px"
            :src="row.avatar"
            :preview-src-list="[row.avatar]"
            preview-teleported
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" min-width="100">
        <template #default="{ row }">
          <el-tag type="info" v-if="row.gender === 0" effect="plain">保密</el-tag>
          <el-tag type="danger" v-if="row.gender === 1" effect="plain">男</el-tag>
          <el-tag type="danger" v-if="row.gender === 2" effect="plain">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="手机号码" min-width="120" sortable />
      <el-table-column prop="email" label="电子邮箱" min-width="120" sortable show-overflow-tooltip />
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.status === 0" effect="plain">正常</el-tag>
          <el-tag type="danger" v-if="row.status === 1" effect="plain">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" min-width="120" sortable show-overflow-tooltip />
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" v-auth="'user:assign-role'" icon="Postcard" @click="openAssign(row)">
            分配角色
          </el-link>
          <el-divider v-auth="'user:update'" direction="vertical" />
          <el-link type="success" v-auth="'user:update'" icon="edit" @click="openEdit(row)"> 编辑 </el-link>
          <el-divider v-auth="'user:delete'" direction="vertical" />
          <el-link type="danger" icon="remove" @click="handleRemove([row.id])"> 删除 </el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt10"
      :current-page="state.pageIndex"
      :page-size="state.pageSize"
      :total="state.page.total"
      :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
      layout="total, sizes, ->, prev, pager, next, jumper"
      background
      @current-change="getTableData"
      @size-change="handleSizeChange"
    />

    <el-dialog v-model="state.showEdit" :title="state.dialogTitle" @close="handleClose">
      <el-form ref="userFormRef" :model="state.userForm" :rules="state.userRules" label-width="100px">
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户名称" prop="username">
              <el-input v-model="state.userForm.username" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
          <el-col v-if="!state.userForm.id" :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="state.userForm.password" type="password" show-password placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="state.userForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户性别" prop="gender">
              <el-radio-group v-model="state.userForm.gender">
                <el-radio-button :value="0">保密</el-radio-button>
                <el-radio-button :value="1">男</el-radio-button>
                <el-radio-button :value="2">女</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="手机号码" prop="mobile">
              <el-input type="tel" v-model="state.userForm.mobile" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="电子邮箱" prop="email">
              <el-input type="tel" v-model="state.userForm.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户状态" prop="status">
              <el-radio-group v-model="state.userForm.status">
                <el-radio border :value="0">启用</el-radio>
                <el-radio border :value="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="用户备注" prop="remark">
              <el-input type="textarea" v-model="state.userForm.description" placeholder="请输入用户备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="state.showEdit = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="state.assignTitle" v-model="state.assignVisible">
      <el-table ref="roleTableRef" :data="state.roleData" border stripe @selection-change="handleRoleCheck">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="code" label="角色编码" min-width="120" sortable />
        <el-table-column prop="description" label="角色描述" min-width="120" show-overflow-tooltip />
      </el-table>

      <template #footer>
        <el-button @click="state.assignVisible = false">取消</el-button>
        <el-button type="primary" @click="assignRole">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
